package com.zxy.controller;

import com.zxy.annotation.RequestMapping;
import com.zxy.annotation.RequestMappingHandler;
import com.zxy.utils.Constants;
import com.zxy.utils.JsonConfigUtil;
import com.zxy.utils.OKHttpUtil;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author zxy
 * @date 2019-04-28 13:41
 */
@WebServlet(name = "weather", urlPatterns = "/weather/*")
public class WeatherController extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) {
        String requestURI = request.getRequestURI();
        String action = requestURI.substring(request.getServletContext().getContextPath().length() + 1);
        action = action.substring(action.indexOf("/") + 1);
        RequestMappingHandler.handle(this.getClass(), this, action, request, response);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        doPost(req, resp);
    }

    @RequestMapping("/forecast")
    public void forecast(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter out = response.getWriter();
        request.setCharacterEncoding("utf-8");
        String amp_webapp_key = JsonConfigUtil.getJsonConfigValue("amap_webapp_key");
        String adcode = request.getParameter("adcode");
        String url = "http://restapi.amap.com/v3/weather/weatherInfo?key=" + amp_webapp_key + "&city=" + adcode + "&extensions=all";
        String result = (String) OKHttpUtil.get(url, Constants.REQUEST_STRING);
        out.write(result);
    }

    @RequestMapping("/forecast")
    public void live(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        String amp_webapp_key = JsonConfigUtil.getJsonConfigValue("amap_webapp_key");
        String adcode = request.getParameter("adcode");
        String url = "http://restapi.amap.com/v3/weather/weatherInfo?key=" + amp_webapp_key + "&city=" + adcode + "&extensions=base";
        String result = (String) OKHttpUtil.get(url, Constants.REQUEST_STRING);

        out.write(result);
    }

}
